<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>万年历</title>
<style>
* {
    padding: 0;
    margin: 0;
    list-style: none;
}

#calendar {
    width: 700px;
    margin: 100px auto;
    text-align: center;
    
    background-color: lightgray;
}

#month_year {

}

ul {
    width: 700px;
}

ul::after {
    content: "";
    display: block;
    clear: both;
}

ul > li {
    width: 100px;
    height: 50px;
    float: left;
    
    text-align: center;
    line-height: 50px;
}
</style>
</head>
<body>
<div id="calendar">
    <div id="month_year">
        <select id="year">
        </select>年
        <select id="month">
        </select>月
    </div>
    <ul>
        <li>星期日</li>
        <li>星期一</li>
        <li>星期二</li>
        <li>星期三</li>
        <li>星期四</li>
        <li>星期五</li>
        <li>星期六</li>
    </ul>
    <ul id="dates">
    
    </ul>
</div>
<script>
var yearSelect = document.getElementById("year");
var monthSelect = document.getElementById("month");
var datesUl = document.getElementById("dates");

function init(){
    // 给yearSelect初始化值
    for (var year = 1900; year < 3000; year++){
        createOption(year, year, yearSelect);
    }

    //给monthSelect初始化值
    for (var month = 1; month <= 12; month++){
        createOption(month, month, monthSelect);
    }

    // 让两个select显示当前的年和月
    var now = new Date();
    selectShow(now.getFullYear(), now.getMonth() + 1);

    showDates();

}

init()

/**
 * 根据当前的select中的年和月来显示日期
 */
function showDates(){
    var year = yearSelect.value;  // 获取目前select中的年份
    var month = monthSelect.value;

    //添加内容为空的li
    var firstDate = new Date(year, month - 1, 1)
    var day = firstDate.getDay();
    for (var i = 0; i < day; i++){
        createLi("", datesUl)
    }
    // 再添加具体的日期的li
    var dates = getDatesOfMonth(year, month);
    for(var i = 1; i <= dates; i++){
        createLi(i, datesUl);
    }
}

/**
 *  创建一个li,并把这个li添加到指定的父节点中
 */
function createLi(text, parent){
    var li = document.createElement("li");
    li.innerHTML = text;
    parent.appendChild(li);
}

/**
 根据参数在select中显示指定的年和月

 */
function selectShow(year, month){
    yearSelect.value = year;
    monthSelect.value = month;
}

/**
 * 创建一个option
 * @param text  option展示的文本
 * @param value option的value值
 * @param parent    option的父节点
 */
function createOption(text, value, parent){
    var opt = document.createElement("option");
    opt.innerHTML = text;
    opt.value = value;
    parent.appendChild(opt);
}

/**
 * 计算指定年月有多少天
 * @param year
 * @param month
 * @return {number}
 */
function getDatesOfMonth(year, month){  // month 是平常的月份
    var d = new Date(year, month, 0);
    return d.getDate();
}
</script>
</body>
</html>